package com.yunyao.web.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.yunyao.common.dto.SpReconciliationDto;
import com.yunyao.common.dto.SpReconciliationOrderDto;
import com.yunyao.common.dto.excel.ReconciliationExcelDto;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.YResult;
import com.yunyao.framework.dto.file.FileInfoDto;
import com.yunyao.framework.dto.posyupply.PoSyupplyMaterialDto;
import com.yunyao.framework.dto.spreconciliatioin.*;
import com.yunyao.framework.service.PoSyupplyOrderService;
import com.yunyao.framework.service.SpReconciliationOrderService;
import com.yunyao.framework.service.SpReconciliationService;
import com.yunyao.framework.vo.posupply.PoSyupplyMaterialVO;
import com.yunyao.framework.vo.spreconciliation.*;
import com.yunyao.web.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/spreconciliation")
public class SpReconciliationController {

    @Autowired
    private SpReconciliationService spReconciliationService;
    @Autowired
    private SpReconciliationOrderService spReconciliationOrderService;
    @Autowired
    private PoSyupplyOrderService poSyupplyOrderService;

    /**
     * 获取供应商对账列表
     *
     * @param spReconciliationDto
     * @return
     */
    @GetMapping("/list")
    public YResult<PageResult<SpReconciliationVO>> getList(SpReconciliationDto spReconciliationDto) {
        return spReconciliationService.pageList(spReconciliationDto);
    }

    /**
     * 获取供应商对账详情信息
     *
     * @param spReconciliationDto
     * @return
     */
    @GetMapping("/info")
    public YResult<SpReconciliationInfoVO> getInfo(SpReconciliationDto spReconciliationDto) {
        return spReconciliationService.getInfo(spReconciliationDto);
    }

    /**
     * 供应商-对账历史金额
     */
    @GetMapping("/getSupplySettlementSum")
    public YResult<BigDecimal> getSupplySettlementSum(@NotBlank String contractId){
        return YResult.success(spReconciliationService.getSupplySettlementSum(contractId));
    }

    /**
     * 保存供应商对账信息
     *
     * @param saveDto
     * @return
     */
    @PostMapping("/save")
    public YResult<String> saveInfo(@RequestBody SpReconciliationSaveDto saveDto) {
        return spReconciliationService.save(saveDto);
    }
    @PostMapping("/delete")
    public YResult<Boolean> deleteInfo(@RequestBody SpReconciliationSaveDto saveDto) {
        return spReconciliationService.deleteInfo(saveDto);
    }
    /**
     * 获取项目对账材料列表
     *
     * @return
     */
    @GetMapping("/material/list")
    public YResult<PageResult<SpReconciliationMaterialVO>> getSpReconciliationMaterialList(SpReconciliationMaterialDto spReconciliationMaterialDto) {
        return spReconciliationOrderService.getSpReconciliationMaterialList(spReconciliationMaterialDto);
    }

    @GetMapping("/material/count")
    public YResult<SpReconciliationMaterialCountVO> getReconciliationMaterialCount(SpReconciliationDto spReconciliationDto) {
        return spReconciliationOrderService.getSpReconciliationMaterialCount(spReconciliationDto);
    }
    /**
     * 保存供应商对账材料信息
     *
     * @param saveDto
     * @return
     */
    @PostMapping("/material/save")
    public YResult<String> saveMaterialInfo(@RequestBody SpReconciliationMaterialSaveDto saveDto) {
        return spReconciliationOrderService.saveMaterialInfo(saveDto);
    }

    /**
     * 删除供应商对账材料信息
     *
     * @param deletedDto
     * @return
     */
    @PostMapping("/material/deleted")
    public YResult<String> deletedMaterialInfo(@RequestBody SpReconciliationMaterialDeleteDto deletedDto) {
        return spReconciliationOrderService.deletedMaterialInfo(deletedDto);
    }
    /**
     * 获取供货材料列表
     *
     * @return
     */
    @GetMapping("/PoSupplymaterial/list")
    public YResult<PageResult<PoSyupplyMaterialVO>> getContractMaterialList(PoSyupplyMaterialDto poSyupplyMaterialDto) {
        return poSyupplyOrderService.getPoSupplyMaterialListbySupplyId(poSyupplyMaterialDto);
    }

    @GetMapping("/order/list")
    public YResult<PageResult<SpReconciliationOrderVO>> getReconciliationPosupplyList(SpReconciliationOrderDto spReconciliationOrderDto) {
        return spReconciliationOrderService.getSpReconciliationPoSupplyList(spReconciliationOrderDto);
    }

    /**
     * 获取供应商对账验收清单列表
     *
     * @return
     */
    @GetMapping("/posupply/list")
    public YResult<PageResult<SpReconciliationPoSupplyVO>> getSpReconciliationSosupplyList(SpReconciliationPoSupplyDto spReconciliationPoSupplyDto) {
        return spReconciliationOrderService.getSpReconciliationPoSupplyList(spReconciliationPoSupplyDto);
    }


    /**
     * 保存供应商对账验收清单信息
     *
     * @param saveDto
     * @return
     */
    @PostMapping("/posupply/save")
    public YResult<String> saveSoSupplyInfo(@RequestBody SpReconciliationPoSupplySaveDto saveDto) {
        return spReconciliationOrderService.savePoSupplyInfo(saveDto);
    }

    /**
     * 删除供应商对账验收清单信息
     *
     * @param deletedDto
     * @return
     */
    @PostMapping("/posupply/deleted")
    public YResult<String> deletedMaterialInfo(@RequestBody SpReconciliationPoSupplyDeletedDto deletedDto) {
        return spReconciliationOrderService.deletedPoPupplyInfo(deletedDto);
    }

    /**
     * 供应商对账确认
     *
     * @param spReconciliationConfirmDto
     * @return
     */
    @PostMapping("/confirm")
    public YResult<String> confirm(@RequestBody @Validated SpReconciliationConfirmDto spReconciliationConfirmDto) {
        return spReconciliationService.confirm(spReconciliationConfirmDto);
    }
    @PostMapping("/check")
    public YResult<String> check(@RequestBody @Validated SpReconciliationConfirmDto spReconciliationConfirmDto) {
        return spReconciliationService.check(spReconciliationConfirmDto);
    }
    @PostMapping("/ycconfirm")
    public YResult<String> ycconfirm(@RequestBody @Validated SpReconciliationConfirmDto spReconciliationConfirmDto) {
        return spReconciliationService.ycconfirm(spReconciliationConfirmDto);
    }
    /**
     * 提交审批供应商对账信息
     *
     * @return
     */
    @PostMapping("/submit/approval")
    public YResult<String> submitApproval(@RequestBody @Validated SpReconciliationSubmitApprovalDto approvalDto) {
        return spReconciliationService.submitApproval(approvalDto);
    }

    /**
     * 审批
     *
     * @return
     */
    @PostMapping("/approval")
    public YResult<String> approval(@RequestBody @Validated SpReconciliationApprovalDto approvalDto) {
        return spReconciliationService.approval(approvalDto);
    }
    /**
     * 导出文件
     *
     * @return
     */

    @GetMapping("/export/file")
    public YResult<String> exportFile(SpReconciliationDto spReconciliationDto, HttpServletResponse response) {
        try {
            List<ReconciliationExcelDto> contractMaterialExportDtoList =  spReconciliationService.export(spReconciliationDto);
            try {
                // 这里URLEncoder.encode可以防止中文乱码
                String fileName = URLEncoder.encode("spreconciliation", String.valueOf(StandardCharsets.UTF_8))+".xlsx";
//                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
                //设置sheet名
                ExportParams params = new ExportParams();
                params.setSheetName("对账信息模版");
                //设置标题
//                params.setTitle("商品信息");
                // 这里需要设置不关闭流
                Workbook workbook = ExcelExportUtil.exportExcel(params, ReconciliationExcelDto.class, contractMaterialExportDtoList);
                //输出流
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                workbook.write(bos);
                byte[] bytes = bos.toByteArray();
                bos.close();
                try {
                    FileInfoDto fileInfoDto = AliOssUtil.upload(bytes,
                            fileName, null);
                    if (null != fileInfoDto) {
                        return YResult.success(fileInfoDto.getLink());
                    } else {
                        return YResult.error("连接文件服务器失败，请重试");
                    }
                } catch (Exception e) {
                    return YResult.error("下载失败，请重试");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }catch (Exception e) {
            log.error("导出对账信息失败",e);
        }
        return YResult.error("导出对账信息失败");
    }
}
